package com.wwdx.controller.rest;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wwdx.controller.base.BaseController;
import com.wwdx.model.WwdxBookClassifyModel;
import com.wwdx.model.WwdxBookModel;
import com.wwdx.model.WwdxThemeModel;
import com.wwdx.model.dto.HomeBean;
import com.wwdx.model.dto.ResultBean;
import com.wwdx.model.dto.WwdxBookBusinessDTO;
import com.wwdx.utils.ConstantHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author liguoliang
 * @date 2017-8-9
 */
@RestController
@RequestMapping("home")
@Api(tags = "首页接口")
public class RestHomeController extends BaseController{

    /**
     * 验证token是否正确
     */
    @RequestMapping("/valid/token")
    @ApiOperation(value = "验证token是否正确",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "令牌",required = true),
            @ApiImplicitParam(name = "sign",value = "签名",required = true)
    })
    public ResultBean validToken(String token, String sign){
        return super.validSignTokenResult(super.getSortedMap(token,sign));
    }

    /**
     * app首页接口
     */
    @RequestMapping("/**")
    @ApiOperation(value = "首页",httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "令牌",required = true),
            @ApiImplicitParam(name = "sign",value = "签名",required = true)
    })
    public ResultBean home(String token, String sign){
        ResultBean resultBean = super.validSignResult(super.getSortedMap(token,sign));
        if (resultBean.getStatus() == 1){
            return resultBean;
        }
        String unionid = wwdxPersonalService.getByToken(token);
        HomeBean homeBean = new HomeBean();
        //轮播图
        homeBean.setBanner_list(wwdxBannerService.banner());
        WwdxThemeModel model = WwdxThemeModel.builder().ishost(1).type(0).status(0).build();
        //精品包
        homeBean.setTheme_list(productService.themeList(wwdxThemeService.selectModelList(model,1, 10), unionid));
        //推荐书单
        model.setType(1);
        homeBean.setBag1(productService.themeList(wwdxThemeService.selectModelList(model, 1, 10), unionid));
        //小课
        WwdxBookModel wwdxBookModel = WwdxBookModel.builder().ishost(1).type(1).status(0).build();
        homeBean.setSmallBook(productService.bookList(wwdxBookService.selectModelList(wwdxBookModel,1,10), unionid));
        //每日听书
        wwdxBookModel.setType(0);
        homeBean.setBook_list(productService.bookList(wwdxBookService.selectModelList(wwdxBookModel,1,1), unionid));
        //热听好书(随机10本书)
        wwdxBookModel.setIshost(null);wwdxBookModel.setRandom(true);
        homeBean.setBook_list2(productService.bookList(wwdxBookService.selectModelList(wwdxBookModel,1,10), unionid));
        //书籍分类
        homeBean.setBookClassifyList(wwdxBookClassifyService.findBookList(0L));
        return renderSuccess(homeBean);
    }

    /**
     * 书籍分类下的标签及书籍列表
     * @param id 分类ID
     */
    @RequestMapping("/classify")
    @ApiOperation(value = "书籍分类",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "令牌",required = true),
            @ApiImplicitParam(name = "sign",value = "签名",required = true),
            @ApiImplicitParam(name = "id",value = "分类ID",required = true)
    })
    public ResultBean classify(String token, String sign, Long id){
        SortedMap<String, Object> sortedMap = super.getSortedMap(token, sign);
        sortedMap.put("id",id);
        ResultBean resultBean = super.validSignResult(sortedMap);
        if (resultBean.getStatus() == 1){
            return resultBean;
        }
        String unionid = wwdxPersonalService.getByToken(token);
        List<WwdxBookClassifyModel> tabList = wwdxBookClassifyService.findBookList(id);
        for (WwdxBookClassifyModel wwdxBookClassifyModel : tabList) {
            wwdxBookClassifyModel.setBookList(this.getBookList(wwdxBookClassifyModel.getId(),unionid));
        }
        return renderSuccess(tabList);
    }

    private List<WwdxBookBusinessDTO> getBookList(Long id, String unionid){
        List<WwdxBookClassifyModel> list = wwdxBookClassifyService.findBookList(id);
        List<WwdxBookModel> bookModels = Lists.newArrayListWithExpectedSize(list.size());
        list.forEach(wwdxBookClassifyModel -> bookModels.add(wwdxBookService.getByBookId(wwdxBookClassifyModel.getBookid())));
        return productService.bookList(bookModels, unionid);
    }

    /**
     * 官方首页
     */
    @RequestMapping("/website")
    @ApiIgnore
    public ResultBean website(){
        Map<String, Object> map = Maps.newHashMapWithExpectedSize(6);
        //最难七本书
        map.put("model1",wwdxThemeService.getByThemeId(1504235755L));
        //重读经典
        map.put("model2",wwdxThemeService.getByThemeId(1504863683L));
        //互联网
        map.put("model3",wwdxThemeService.getByThemeId(1504236713L));
        //99%
        map.put("model4",wwdxThemeService.getByThemeId(1504518794L));
        //如何掌控未来
        map.put("model5",wwdxThemeService.getByThemeId(1504178594L));
        //品读人生传奇
        map.put("model6",wwdxThemeService.getByThemeId(1504234687L));
        return renderSuccess(map);
    }

    /**
     * 小程序首页
     */
    @RequestMapping("/ma")
    @ApiOperation(value = "小程序首页",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "令牌",required = true),
            @ApiImplicitParam(name = "sign",value = "签名",required = true)
    })
    public ResultBean mahome(String token, String sign){
        ResultBean resultBean = super.validSignResult(super.getSortedMap(token,sign));
        if (resultBean.getStatus() == 1){
            return resultBean;
        }
        String unionid = wwdxPersonalService.getByToken(token);
        return renderSuccess(productService.themeList(wwdxThemeService.selectModelList(WwdxThemeModel
                .builder().type(2).build(),1,2), unionid));
    }

    /**
     * 查询用户是否订阅
     */
    @RequestMapping("/subscribe/get")
    public ResultBean subscribeget(String openId,String logoId){
        Preconditions.checkArgument(StringUtils.isNotBlank(openId),"openId is null");
        Map<String,Object> map = Maps.newHashMapWithExpectedSize(2);
        map.put("logo",logoId);
        //判断是否订阅
        Boolean member = setOperations.isMember(ConstantHolder.USER_SUBSCRIBE_TOTAL_TS_SET, openId);
        if (member)return renderSuccess(map);else return new ResultBean(1,"用户未订阅",map);
    }

//    @RequestMapping("/subscribe/get")
//    public ResultBean subscribeget(String unionid){
//        Preconditions.checkArgument(StringUtils.isNotBlank(unionid),"unionid is null");
//        return renderSuccess(setOperations.isMember(ConstantHolder.USER_SUBSCRIBE_TOTAL_SET, unionid));
//    }

    /**
     * 保存用户订阅记录
     */
    @RequestMapping("/subscribe/add")
    public ResultBean subscribeadd(String openId){
        Preconditions.checkArgument(StringUtils.isNotBlank(openId),"openid is null");
        Boolean member = setOperations.isMember(ConstantHolder.USER_SUBSCRIBE_TOTAL_TS_SET, openId);
        //如果不存在，则为新订阅用户
        if (!member){
            //新增用户
            setOperations.add(ConstantHolder.USER_SUBSCRIBE_TOTAL_TS_SET, openId);
        }
        return renderSuccess();
    }
//    @RequestMapping("/subscribe/add")
//    public ResultBean subscribeadd(String unionid){
//        Preconditions.checkArgument(StringUtils.isNotBlank(unionid),"unionid is null");
//        Boolean member = setOperations.isMember(ConstantHolder.USER_SUBSCRIBE_TOTAL_SET, unionid);
//        String date = new LocalDate().toString();
//        //如果不存在，则为新订阅用户
//        if (!member){
//            //新增用户
//            String subscribeNewKey = String.format(ConstantHolder.USER_SUBSCRIBE_NEW_SET, date);
//            setOperations.add(subscribeNewKey,unionid);
//            redisTemplate.expire(subscribeNewKey,30 * 60 * 60 , TimeUnit.SECONDS);
//            setOperations.add(ConstantHolder.USER_SUBSCRIBE_TOTAL_SET, unionid);
//        }
//        return renderSuccess();
//    }

    /**
     * 新手专区
     * @param unionid 用户业务ID
     */
    @RequestMapping("/novice/list")
    @ApiOperation(value = "新手专区书籍列表",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "unionid",value = "用户业务ID",required = true)
    })
    public ResultBean novicelist(@RequestParam("unionid") String unionid){
        List<Object> range = listOperations.range(ConstantHolder.NOVICE_BOOK_LIST, 0, -1);
        List<WwdxBookModel> wwdxBookModels = Lists.newArrayListWithExpectedSize(range.size());
        range.forEach(bookid -> wwdxBookModels.add(wwdxBookService.getByBookId(Long.valueOf(bookid.toString()))));
        return renderSuccess(productService.bookList(wwdxBookModels,unionid));
    }
}